<template>
  <div>
    <n-upload
      ref="uploadRef"
      :data="{ folder: 'video', id: id }"
      :default-upload="false"
      name="files"
      multiple
      v-model:file-list="fileList"
      @change="handleChange"
    >
      <n-button>选择文件</n-button>
    </n-upload>
    <div>
      <n-button
        v-if="fileList.length"
        type="primary"
        style="margin-bottom: 12px"
        @click="handleClick"
        :loading="loading"
      >
        开始上传
      </n-button>
    </div>
  </div>
</template>

<script lang="ts" setup>
  import { useMessage, type UploadFileInfo, type UploadInst } from 'naive-ui';
  import { onMounted, ref, watch } from 'vue';
  import TcVod from 'vod-js-sdk-v6';
  import { getVideoToken, putVideo } from '@/api/video/video';
  import { ResultEnum } from '@/enums/httpEnum';
  // https://license.vod2.myqcloud.com/license/v2/1254102485_1/v_cube.license
  // fe1bb84ac7183e7c3d9f5522bd631046
  const fileList = ref<UploadFileInfo[]>([]);
  const fileRes = ref<any>([]);
  const uploadRef = ref<UploadInst | null>(null);
  const message = useMessage();
  const loading = ref<boolean>(false);
  // eslint-disable-next-line vue/no-dupe-keys
  const id = ref(0);
  const _index = ref(0);

  const props = defineProps<{
    data: any;
    id: any;
  }>();

  watch(
    () => props,
    () => {
      fileList.value = props.data;
      id.value = props.id;
    },
    { immediate: true }
  );

  const handleChange = (options: { fileList: UploadFileInfo[] }) => {
    fileList.value = options.fileList;
  };

  const handleClick = () => {
    upload();
  };

  const upload = () => {
    let file: any = fileList.value[_index.value].file;
    const tcVod = new TcVod({
      getSignature: getSignature, // 前文中所述的获取上传签名的函数
    });
    const uploader = tcVod.upload({
      mediaFile: file, // 媒体文件（视频或音频或图片），类型为 File
    });
    uploader.on('media_progress', function (info) {
      fileList.value[_index.value].status = 'uploading';
      fileList.value[_index.value].percentage = parseInt(info.percent * 100);
    });
    loading.value = true;
    uploader
      .done()
      .then(function (doneResult) {
        //每上传成功就保存一次
        // ['title','duration','size','file_url','play_url','file_id','sort','status'];
        onSaveVideo(doneResult);
        _index.value++;
        if (fileList.value.length == _index.value) {
          message.info('文件全部上传完成');
          loading.value = false;
          return false;
        }

        upload();
        console.log(doneResult);
      })
      .catch(function (err) {
        console.log(err);
        // deal with error
      });
    // uploadRef.value?.submit();
  };

  const emit = defineEmits(['saveVideo']);
  const onSaveVideo = async (data: any) => {
    let obj: any = {
      title: fileList.value[_index.value].name,
      file_id: data.fileId,
      file_url: data.video.url,
      id: id.value,
    };
    const response: any = await putVideo(obj);
    if (response.code === ResultEnum.SUCCESS) {
      fileRes.value.push(response.data);
      message.info('视频保存成功');
    }
    if (_index.value == fileList.value.length) {
      emit('saveVideo', fileRes.value);
    }
  };

  async function getSignature() {
    const sign: any = await getVideoToken();
    return sign.data;
  }

  onMounted(() => {
    // getTypes();
  });
</script>
